package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessPersonnelService;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ActivityTypeVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.PingZhongVo;
import com.digitalchina.lxnsy.entity.SheepVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

import static com.digitalchina.lxnsy.toolkit.DateUtil.DateToString;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/9/8 10:36
 * 修改备注：
 * ================================================
 */
public class AddSheepActivity extends BaseActivity {
    @Bind(R.id.tv_post_task)
    EditText tvPostTask;
    @Bind(R.id.tv_contact_people)
    EditText tvContactPeople;
    @Bind(R.id.tv_variety)
    TextView tvVariety;
    @Bind(R.id.tv_grade)
    TextView tvGrade;
    @Bind(R.id.tv_people_num)
    EditText tvPeopleNum;
    @Bind(R.id.tv_price)
    EditText tvPrice;
    @Bind(R.id.tv_address)
    EditText tvAddress;
    @Bind(R.id.tv_tel)
    EditText tvTel;
    @Bind(R.id.tv_start_date)
    TextView tvStartDate;
    @Bind(R.id.tv_end_date)
    TextView tvEndDate;
    @Bind(R.id.post_task)
    TextView postTask;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;

    /**
     * 发布人才需求
     * id       需求或供应Id   新发布为空
     * content      任务内容
     * contactPeople 联系人
     * peopleNum    人数
     * price        价格
     * address      详细地址
     * tel          联系电话
     * startTime    开始时间
     * endTime      结束时间
     * demandCode   招聘要求编码
     * provinceCode 省份编码
     * cityCode     城市编码
     * countyCode   区县编码
     */
    private String id = "";
    private String content = "";
    private String contactPeople = "";
    private String peopleNum = "";
    private String price = "";
    private String address = "";
    private String tel = "";
    private String startTime = "";
    private String endTime = "";
    private String variety = "";
    private String grade = "";
    private String imgs = "";

    private String types = "";

    // 时间选择器
    private TimePickerView pvTime;
    // 区分开始和结束时间
    private int type = -1;
    // 发布类型
    private String postType = "";

    private List<PingZhongVo> typeList;
    // 品种
    private OptionsPickerView pvTitle;

    private List<ActivityTypeVO> gradeList = new LinkedList<>();
    // 品种
    private OptionsPickerView gradeTitle;
    // 选择图片
    public static final int REQUEST_CODE_SELECT = 100;


    private SheepVO vo;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_sleep_demand);
    }

    @Override
    public void initMember() {
        selectImage();
        initTimePicker();
        initGrade();
        BusinessPersonnelService.getTalentTitles(this, mHandler);
        Map<String, Object> map = (Map<String, Object>) getIntent().getSerializableExtra("map");
        postType = map.get("postType").toString();

        if (postType.equals("editDemand")) {
            setTitle("发布良种羊需求");
            postTask.setText("任务内容");
            types = "1";
        } else {
            setTitle("发布良种羊供应");
            postTask.setText("服务内容");
            types = "0";
        }

        if (map.containsKey("data"))
            vo = (SheepVO) map.get("data");
        if (vo != null) {
            id = vo.getId();
            content = vo.getContent();
            contactPeople = vo.getContacts();
            peopleNum = vo.getNumber() + "";
            price = vo.getPrice()+"";
            address = vo.getAddress();
            tel = vo.getTelephone();
            startTime = vo.getStartDate();
            endTime = vo.getEndDate();
            variety = vo.getBreedName();
            imgs = vo.getUploadImgs();
            grade = vo.getGrade();
            // 任务名
            tvPostTask.setText(content);
            // 联系人
            tvContactPeople.setText(contactPeople);
            // 人数
            tvPeopleNum.setText(peopleNum);
            // 价格
            tvPrice.setText(price);
            tvVariety.setText(variety);
            tvGrade.setText(grade);
            // 详细
            tvAddress.setText(address);
            // 电话
            tvTel.setText(tel);
            setImageView(imgs);
            // 起始日期
            if (!StringUtil.isStrEmpty(startTime) && startTime.length() >= 10)
                tvStartDate.setText(startTime.substring(0, 10));
            else
                tvStartDate.setText(startTime);
            // 结束日期
            if (!StringUtil.isStrEmpty(endTime) && endTime.length() >= 10)
                tvEndDate.setText(endTime.substring(0, 10));
            else
                tvStartDate.setText(endTime);

        }
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GET_TALENT_TITLES_SUCCESS: // 品种
                        callBack(msg.obj.toString());
                        break;
                    case MSG.MSG_LOGIN_SUCCESS:// 发布成功
                        showToast("发布成功");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_LOGIN_FAILED:// 发布失败
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS:  // 上传图片
                        dismissDialog();
                        try {
                            String value = new JSONObject(msg.obj.toString()).getString("value");
                            setImageView(value);
                            imgs = value;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        break;

                }
            }
        };
    }

    private void setImageView(String fileName) {
        FrescoUtil.showImageSmall(fileName, sdvImg0);
    }

    private void initGrade() {

        ActivityTypeVO activityTypeVO = new ActivityTypeVO();
        activityTypeVO.setLabel("特级");
        gradeList.add(activityTypeVO);
        ActivityTypeVO activityTypeVO1 = new ActivityTypeVO();
        activityTypeVO1.setLabel("一级");
        gradeList.add(activityTypeVO1);
        ActivityTypeVO activityTypeVO2 = new ActivityTypeVO();
        activityTypeVO2.setLabel("二级");
        gradeList.add(activityTypeVO2);
        ActivityTypeVO activityTypeVO3 = new ActivityTypeVO();
        activityTypeVO3.setLabel("三级");
        gradeList.add(activityTypeVO3);
        gradeTitle = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tvGrade.setText(gradeList.get(options1).getLabel());
                grade = gradeList.get(options1).getLabel();
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        gradeTitle.setPicker(gradeList);
    }
    @Override
    public void callBack(Object object) {
        typeList = FastJsonUtil.getListBeanRow(object.toString(), "rows", PingZhongVo.class);
        pvTitle = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tvVariety.setText(typeList.get(options1).getName());
                variety = typeList.get(options1).getName();
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvTitle.setPicker(typeList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.rl_post_task, R.id.rl_variety,R.id.rl_grade, R.id.rl_start_date, R.id.rl_end_date, R.id.sdv_img0,R.id.btn_post})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_variety:
                if (typeList != null && typeList.size() > 0) {
                    pvTitle.show();
                } else {
                    showToast("正在获取获取品种");
                    BusinessPersonnelService.getTalentTitles(this, mHandler);
                }
                break;
            case R.id.rl_grade:
                gradeTitle.show();
                break;
            case R.id.rl_start_date:
                type = 0;
                pvTime.show();
                break;
            case R.id.rl_end_date:
                type = 1;
                pvTime.show();
                break;
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.btn_post:
                submit();
                break;
        }
    }

    /**
     * 提交数据
     */
    private void submit() {
        content = tvPostTask.getText().toString();
        contactPeople = tvContactPeople.getText().toString();
        peopleNum = tvPeopleNum.getText().toString();
        price = tvPrice.getText().toString();
        address = tvAddress.getText().toString();
        tel = tvTel.getText().toString();
        startTime = tvStartDate.getText().toString();
        endTime = tvEndDate.getText().toString();
        if (StringUtil.isStrEmpty(content)) {
            showToast("请填写任务内容");
            return;
        }

        if (StringUtil.isStrEmpty(contactPeople)) {
            showToast("请填写联系人");
            return;
        }

        if (StringUtil.isStrEmpty(peopleNum)) {
            showToast("请填写数量");
            return;
        }

        if (StringUtil.isStrEmpty(price)) {
            showToast("请填写价格");
            return;
        }

        if (StringUtil.isStrEmpty(variety)) {
            showToast("请选择品种");
            return;
        }
        if (StringUtil.isStrEmpty(grade)) {
            showToast("请选择等级");
            return;
        }

        if (StringUtil.isStrEmpty(address)) {
            showToast("请填写详细地址");
            return;
        }

        if (StringUtil.isStrEmpty(tel)) {
            showToast("请填写联系方式");
            return;
        }

        if (StringUtil.isStrEmpty(startTime)) {
            showToast("请填写开始时间");
            return;
        }

        if (StringUtil.isStrEmpty(endTime)) {
            showToast("请填写结束时间");
            return;
        }

        if (vo != null){
            BusinessPersonnelService.editSleep(this, types, vo.id, content, contactPeople, peopleNum, price, address, tel, startTime, endTime, variety,grade,imgs, mHandler);
        }else {
            BusinessPersonnelService.addSleep(this, types, content, contactPeople, peopleNum, price, address, tel, startTime, endTime, variety,grade,imgs, mHandler);
        }
    }


    /**
     * 所在区域选择
     */
    private void showAddressPicker() {
        final BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
            @Override
            public void onAddressSelected(Province province, City city, County county, Street street) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.show();
    }

    /**
     * 时间选择器
     * 0=开始  1=结束
     */
    private void initTimePicker() {

        int start = 2017;
        int endDate = 2100;

        //控制时间范围,setRange方法 要在setDate 之前才有效果(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        /*Calendar calendar = Calendar.getInstance();*/

        //时间选择器
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                switch (type) {
                    case 0:
                        startTime = DateToString(date, DateStyle.YYYY_MM_DD);
                        tvStartDate.setText(startTime);
                        break;
                    case 1:
                        endTime = DateToString(date, DateStyle.YYYY_MM_DD);
                        tvEndDate.setText(endTime);
                        break;
                }

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//default is all
                .setLabel("年", "月", "日", "", "", "") //设置空字符串以隐藏单位提示   hide label
                .setRange(start, endDate)
                .build();
    }

    private void selectImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);    //是否多选模式
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
    }

    private void selectImage(int ixdex) {
        if (StringUtil.isStrEmpty(imgs)) {
            Intent intent = new Intent(this, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(activity)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgs = "";
                            Uri uri = Uri.parse("res://com.digitalchina.lxnsy/" + R.drawable.selector_image_add);
                            sdvImg0.setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }
            }
        }
    }

}
